#!/usr/bin/env python
import psycopg2
import smtplib as sm
import signal
import time
import sys
import os
import resource
from email.mime.text import MIMEText

"""
Checks for unsent emails from database, sends them from Gmail account via SMTP
and TLS, marks them as sent.
"""

curs = None

end_program = False;

# allow completion of email phase before termination
# also prevent closing due to loss of terminal
def signal_handler(signum, frame):
  global end_program
  end_program = True

def db_connect():
  """Attempts to connect to the database."""
  try:
    return psycopg2.connect("dbname='helpdesk' user='helpdesk' password='kitten44'")
  except Exception, ex:
    print "Error connecting to database:", ex
    return None
    
def mail_connect():
  """Logs into Gmail account through SMTP and TLS."""
  try:
    srv = sm.SMTP('smtp.gmail.com', 587)
    srv.set_debuglevel(1) # causes SMTPLib to output debugging information
    srv.ehlo()
    srv.starttls()
    srv.ehlo()
    srv.login('pitt.distributedithelpdesk', 'idontcare')
    return srv
  except Exception, ex:
    print "Error connecting to email server:", ex
    return None

def send_emails(cur, emails):
  """
  Parses and sends unsent emails from database to specified recipients and then marks them as sent.

  cur is a cursor object
  emails are the emails
  """
  mailer = mail_connect()
  if mailer == None:
    return
  minid = -1 # we will mark all emails in the range we have read as sent
  maxid = 0 
  for email in emails:
    emailid = email[0]
    recipient = email[1]
    title = email[2]
    message = email[3]
    sent = email[4]

    if emailid > maxid:
      maxid = emailid
    if minid != -1 and emailid < minid:
      minid = emailid

    if sent == False:
      msg = MIMEText(message)
      msg['Subject'] = title 
      msg['From'] = 'pitt.distributedithelpdesk@gmail.com'
      msg['To'] = recipient 
      try:
        mailer.sendmail('pitt.distributedithelpdesk@gmail.com', recipient, msg.as_string())
      except Exception, ex:
        print "Could not send e-mail. Skipping..."

  mailer.quit()


  if maxid > 0:
    statement = '''UPDATE emails SET sent = TRUE WHERE emailid >= %d and emailid <= %d''' % (minid,maxid)
    cur.execute(statement)

def helpdesk_mailer():
    print "Connecting to database"
    conn = db_connect()
    if (conn == None):
      return

    print "Fetching emails"
    c = conn.cursor()
    statement = '''SELECT emailid, recipient, title, message, sent FROM emails WHERE sent = FALSE'''
    c.execute(statement)

    emails = c.fetchall()

    if len(emails) > 0:
      print "Sending email"
      send_emails(c, emails)
    else:
      print "No mail to send"

    conn.commit()
    conn.close()

def mailer_main():
  signal.signal(signal.SIGTERM, signal_handler)
  while end_program == False:
    helpdesk_mailer()
    time.sleep(10)

if __name__ == '__main__':
  mailer_main()

